package main

import (
	"encoding/json"
	"fmt"
	"go.manyji.com/lib/util/convert"
)

func Recharge(activityId int64, deviceId string) (*PayPalCreateOrderResponse, error) {

	repMap := map[string]interface{}{}
	rData, err := recharge(activityId, deviceId)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal([]byte(rData), &repMap)
	if err != nil {
		return nil, err
	}

	dataMap, ok := repMap["Data"].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("%v", repMap["ErrMsg"])
	}

	var resp = &PayPalCreateOrderResponse{
		ID:          convert.ToString(dataMap["id"]),
		PaymentLink: convert.ToString(dataMap["paymentLink"]),
	}

	for _, v := range dataMap["links"].([]interface{}) {
		pp := v.(map[string]interface{})
		ppl := PayPalLink{
			Href:   convert.ToString(pp["href"]),
			Rel:    convert.ToString(pp["rel"]),
			Method: convert.ToString(pp["method"]),
		}
		resp.Links = append(resp.Links, ppl)
	}

	return resp, nil
}

func RechargeCallBack(status, timeout int, orderNo, deviceId string) error {
	res, err := rechargeFeedBack(status, timeout, orderNo, deviceId)
	if err != nil {
		return err
	}
	resData := &ApiRep[map[string]interface{}]{}
	err = json.Unmarshal([]byte(res), &resData)
	if err != nil {
		return err
	}
	if resData.Code != 0 {
		return fmt.Errorf(resData.ErrMsg)
	}

	return nil
}
